﻿using CommunityToolkit.Maui.Views;
using Microsoft.Maui.Controls;

namespace ZiChen.SoXunLeiPan.ViewModel
{
    public class MenuPopup : Popup
    {
        public MenuPopup()
        {
            var menuLayout = new StackLayout
            {
                BackgroundColor = Colors.White,
                Padding = new Thickness(10),
                Spacing = 15,
                MinimumWidthRequest = 150,
            };

            // 封装创建菜单项的方法，减少重复代码
            menuLayout.Children.Add(CreateMenuItem("最新收录"));
            menuLayout.Children.Add(CreateMenuItem("热门资源"));
            menuLayout.Children.Add(CreateMenuItem("帮助中心"));

            this.Content = menuLayout;
            this.CanBeDismissedByTappingOutsideOfPopup = true;
        }

        // 封装菜单项创建逻辑
        private Frame CreateMenuItem(string text)
        {
            var label = new Label
            {
                Text = text,
                FontSize = 14,
                TextColor = Colors.Black,
                VerticalOptions = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.Start,
                Padding = new Thickness(5)
            };

            // 使用Frame包裹以提供点击反馈
            var itemContainer = new Frame
            {
                BackgroundColor = Colors.Transparent,
                Padding = 0,
                Margin = 0,
                Content = label,
                CornerRadius = 4
            };

            itemContainer.GestureRecognizers.Add(new TapGestureRecognizer
            {
                // 命令需要标记为async以支持await
                Command = new Command(async () =>
                {
                    // 点击时的视觉反馈
                    itemContainer.BackgroundColor = Colors.LightGray;
                    await Task.Delay(100); // 短暂延迟以显示反馈效果

                    // 使用正确的异步关闭方法
                    await CloseAsync(text);
                })
            });

            return itemContainer;
        }
    }
}
